<!--  -->
<template>
  <div class="system-information-item" v-loading="globalLoading">
    <!-- <div class="header">
      <el-row type="flex" justify="end">
        <el-button type="warning" size="small" v-if="system && system.systemType && system.systemType.id === 3"
          @click="categoryTreeShow">分类级别树形结构</el-button>
        <el-button type="primary" @click="onSubmit" size="small">保存</el-button>
        <el-button type="success" @click="onSubmitAndGoSystemList" size="small">保存并返回系统列表</el-button>
        <el-button size="small" @click="goSystemList">返回系统列表</el-button>
      </el-row>
      <div class="border"></div>
    </div> -->
    <el-form ref="informationForm" :model="information" label-width="180px" v-loading="formLoading">
      <SystemInformationItemForm ref="systemInformationItemForm" :information="information" :changeInformation="changeInformation"
         :globalLoading="globalLoading" :resetImageList="resetImageList"/>
      <el-form-item class="footfixed">
        <el-button type="primary" @click="onSubmit">保存</el-button>
        <el-button type="success" @click="onSubmitAndGoSystemList">保存并返回系统列表</el-button>
        <el-button @click="goSystemList">返回系统列表</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import SystemInformationItemForm from '@/components/main/user/system/information/item/SystemInformationItemForm.vue'
import TreeDialog from '@/components/common/dialog/TreeDialog.vue'
import * as functions from '@/core/functions.js'
export default {
  created () {
    let query = this.$route.query
    if (!query || !query.sid || !query.id) {
      this.$message.error('未能获取到正确的数据')
      return
    }
    let systemId = query.sid
    let id = query.id
    // 获取系统信息
    this.$post('/system/info', { id: systemId }).then((resoponse) => {
      if (resoponse && resoponse.id) {
        this.system = resoponse
        this.information.systemId = this.system.id

        // 获取内容信息
        if (id > 0) {
          // 修改
          this.$post('/system/information/data-info', {id: id}).then(response => {
            if (response) {
              this.information = initInformation(response, this)
            } else {
              console.error(response)
            }
            this.initComplete.titleItem = true
            this.initComplete.data = true
            this.initComplete.attr = true
          })
        } else {
          // 新增
          this.initComplete.data = true
          // 获取信息系统属性
          this.$post('/system/information/title-infos', { systemId: systemId }).then(response => {
            let titleItem = initAttrByInformationAttr(response)
            this.information.titleItem = titleItem
            this.initComplete.titleItem = true
          })
        }
      }
      this.initComplete.system = true
    })
  },
  data () {
    return {
      // 全局加载
      globalLoading: true,
      // 表单加载
      formLoading: false,
      // 判断是否加载完成的四个加载项目
      initComplete: {
        system: false,
        data: false,
        titleItem: false
      },
      // 当前的系统
      system: {},
      // 表单数据
      information: {
        // 基础信息
        id: 0,
        systemId: 0,
        // 状态 （0）-不显示 （1）-显示
        status: 1,
        // 属性信息
        titleItem: [],
        // 文件信息
        file: {},
        fileRepertoryConfig: '',
        fileRepertoryId: null,
        // 图片信息
        imageList: [],
        imageRepertoryId: null,
        imageRepertoryConfig: {}
      }
    }
  },
  computed: {
  },
  watch: {
    initComplete: {
      handler (newVal) {
        this.$nextTick(() => {
          if (newVal.system && newVal.data && newVal.titleItem) {
            // 初始化请求完毕
            this.globalLoading = false
          }
        })
      },
      deep: true
    }
  },
  methods: {
    // 保存
    onSubmit (callback) {
      let bool = true
      this.information.titleItem.forEach(el => {
        if (el.value.trim() !== '') {
          bool = false
        }
      })
      if (bool) {
        this.$message.error('自定义字段不能全部为空！')
        return
      }
      let param = {
        fileRepertoryConfig: this.information.fileRepertoryConfig,
        fileRepertoryId: this.information.fileRepertoryId,
        id: this.information.id,
        imageRepertoryConfig: this.information.imageRepertoryConfig,
        imageRepertoryId: this.information.imageRepertoryId,
        status: this.information.status,
        systemId: this.information.systemId,
        titleItem: JSON.parse(JSON.stringify(this.information.titleItem))
      }
      this.formLoading = true
      this.$jpost('/system/information/data-save', param).then(response => {
        if (response) {
          if (typeof callback === 'function') {
            callback()
          }
          this.information = initInformation(response, this)
        } else {
          console.error(response)
        }
        this.formLoading = false
      })
    },
    // 保存并返回系统列表
    onSubmitAndGoSystemList () {
      this.onSubmit(() => {
        this.goSystemList()
      })
    },
    // 返回系统列表
    goSystemList () {
      let fullPath = functions.getSystemListPathByItem(this.system)
      if (!fullPath) {
        return
      }

      // 存储系统页面页码，如果从编辑页返回列表页fromItem改为true
      let systbPageCur = JSON.parse(sessionStorage.getItem('systbPageCur' + this.system.id))
      if (systbPageCur) {
        systbPageCur.fromItem = true
        sessionStorage.setItem('systbPageCur' + this.system.id, JSON.stringify(systbPageCur))
      }

      this.$store.dispatch('navAppendAndClose', { path: fullPath, close: this.$route.fullPath })
    },
    // 改变download数据
    changeInformation (infos) {
      this.information = infos
    },
    // 重置当前的图片列表
    resetImageList (list) {
      this.information.imageList = list
      if (this.information.imageList.length < 1) {
        this.information.imageRepertoryConfig = {}
        this.information.imageRepertoryId = null
      }
    }
  },
  components: {
    TreeDialog,
    SystemInformationItemForm
  }
}

// 初始化 information 数据使其符合 this.information 中的数据格式
function initInformation (data, vm) {
  let file = data.one && data.one.file && data.one.file.hrepertory && data.one.file.srepertoryQuote ? {
    id: data.one.file.hrepertory.id,
    originalFilename: data.one.file.hrepertory.originalFilename,
    suffix: data.one.file.hrepertory.suffix
  } : {}
  let fileRepertoryId = data.one && data.one.file && data.one.file.hrepertory ? data.one.file.hrepertory.id : null
  let imageList = []
  let imageRepertoryId = null
  let imageRepertoryConfig = {}
  if (data.one && data.one.image && data.one.image.hrepertory && data.one.image.srepertoryQuote) {
    let item = data.one.image.hrepertory
    let quote = data.one.image.srepertoryQuote
    let config
    if (quote.config) {
      config = JSON.parse(quote.config)
    }
    let title = config && config.title ? config.title : item.originalFilename
    let alt = config && config.alt ? config.alt : item.originalFilename

    let repertoryImageSrc = { hostId: vm.$store.state.host.id, repertoryId: item.id, suffix: item.suffix, type: item.type, link: item.link }
    imageList.push({
      id: item.id,
      src: functions.getRepertoryImageSrc(repertoryImageSrc),
      title: title,
      alt: alt
    })
    imageRepertoryId = item.id
    imageRepertoryConfig = {
      title: title,
      alt: alt
    }
  }
  let titleItem = []
  if (data.one && data.one.listItem && data.one.listItem.length > 0 && data.title && data.title.length > 0) {
    data.title.forEach(el => {
      if (el.type === 1) {
        let ite = {
          informationTitleId: el.id,
          title: el.title,
          value: ''
        }
        data.one.listItem.forEach(ele => {
          if (el.id === ele.informationTitleId) {
            ite.value = ele.value
          }
        })
        titleItem.push(ite)
      }
    })
  }
  return {
    id: data.one.data.id,
    systemId: data.system.id,
    status: data.one.data.status,
    titleItem: titleItem,
    file: file,
    fileRepertoryConfig: '',
    fileRepertoryId: fileRepertoryId,
    imageList: imageList,
    imageRepertoryId: imageRepertoryId,
    imageRepertoryConfig: imageRepertoryConfig
  }
}

function initAttrByInformationAttr (data) {
  let result = []
  if (!data || data.length < 1) {
    return []
  }
  data.forEach((element) => {
    if (element.type === 1) {
      result.push({
        informationTitleId: element.id,
        title: element.title,
        value: ''
      })
    }
  })
  return result
}

</script>
<style scoped lang="scss">
.system-information-item {
  padding-bottom: 60px;
  .header {
    min-height: 36px;
    .border {
      width: 100%;
      height: 1px;
      border-bottom: 2px solid #e5e5e5;
      margin-top: 12px;
      margin-bottom: 24px;
    }
  }
}
.footfixed {
  position: fixed;
  z-index: 1000;
  bottom: 0;
  left: 220px;
  right: 0;
  background: #fff;
  padding: 15px 20px;
  border-top: 1px solid #eee;
  margin-bottom: 0 !important;
  text-align: right;
}
</style>
